package com.geeklan.smart.data.remote.oss;

import android.content.Context;
import com.alibaba.sdk.android.oss.*;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.*;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class AsyncMultiFileUploader {
    public static void uploadFiles(Context context, List<String> filePaths, UploadMultifileCallback callback) {
        OSS oss = OSSManager.getOSSClient(context);

        CountDownLatch latch = new CountDownLatch(filePaths.size()); // 用于等待所有任务完成
        final int[] successCount = {0};
        final int[] failureCount = {0};

        for (String filePath : filePaths) {
            String objectKey = ObjectKeyGenerator.generateObjectKey(filePath);
            PutObjectRequest put = new PutObjectRequest(OSSManager.BUCKET_NAME, objectKey, filePath);

            // 异步上传
            oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                    successCount[0]++;
                    if (callback != null) {
                        String objectKey = request.getObjectKey();
                        // 构造文件的完整访问 URL
                        String fileUrl = "https://" + OSSManager.BUCKET_NAME + "." + OSSManager.ENDPOINT + "/" + objectKey;
                        callback.onUploadSuccess(fileUrl);
                    }
                    latch.countDown(); // 任务完成
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                    failureCount[0]++;
                    String error = clientExcepion != null ? clientExcepion.getMessage() : serviceException.getRawMessage();
                    if (callback != null) {
                        callback.onUploadFailure(filePath, error);
                    }
                    latch.countDown(); // 任务完成
                }
            });
        }

        // 等待所有任务完成并回调
        new Thread(() -> {
            try {
                latch.await();
                if (callback != null) {
                    callback.onAllUploadsComplete(successCount[0], failureCount[0]);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

}

